package com.sqlcheck.demo;

import com.sqlcheck.config.SimpleAIParallelConfig;
import com.sqlcheck.service.impl.SimpleBatchProgressTracker;
import com.sqlcheck.service.ProgressCallback;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * AI并行处理功能演示
 * 展示如何使用新的并行处理和简化的进度跟踪功能
 * 
 * @author Claude
 * @version v1.0
 * @since 2025-09-11
 */
@Slf4j
public class AIParallelProcessingDemo {
    
    /**
     * 演示并行处理功能
     */
    public static void demonstrateParallelProcessing() {
        log.info("=== AI并行处理功能演示 ===");
        
        // 1. 创建线程池配置（模拟生产环境）
        ThreadPoolTaskExecutor executor = createExecutor();
        
        // 2. 创建进度跟踪器
        ProgressCallback progressCallback = new DemoProgressCallback();
        SimpleBatchProgressTracker progressTracker = 
            new SimpleBatchProgressTracker(8, progressCallback, "AI增强验证演示");
        
        // 3. 模拟批次数据
        List<MockBatch> batches = createMockBatches(8);
        
        // 4. 并行处理各批次
        log.info("开始并行处理 {} 个批次", batches.size());
        
        List<CompletableFuture<String>> futures = batches.stream()
            .map(batch -> CompletableFuture
                .supplyAsync(() -> processMockBatch(batch, progressTracker), executor)
                .exceptionally(throwable -> {
                    log.error("批次 {} 处理失败", batch.getBatchNumber(), throwable);
                    progressTracker.onBatchError(batch.getBatchNumber(), throwable.getMessage());
                    return "ERROR_" + batch.getBatchNumber();
                }))
            .collect(Collectors.toList());
        
        // 5. 等待所有批次完成
        List<String> results = futures.stream()
            .map(CompletableFuture::join)
            .collect(Collectors.toList());
        
        // 6. 完成最终统计
        long successCount = results.stream().filter(r -> !r.startsWith("ERROR")).count();
        progressTracker.onAllBatchesCompleted((int) successCount);
        
        log.info("=== 演示完成 ===");
        log.info("处理结果: {}", results);
        log.info("成功批次: {}/{}", successCount, batches.size());
        
        // 清理资源
        executor.shutdown();
    }
    
    /**
     * 创建线程池执行器
     */
    private static ThreadPoolTaskExecutor createExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(8);
        executor.setQueueCapacity(20);
        executor.setThreadNamePrefix("demo-ai-");
        executor.setKeepAliveSeconds(60);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
    
    /**
     * 创建模拟批次数据
     */
    private static List<MockBatch> createMockBatches(int count) {
        List<MockBatch> batches = new ArrayList<>();
        for (int i = 1; i <= count; i++) {
            batches.add(new MockBatch(i, "批次" + i, i * 10 + (int)(Math.random() * 50)));
        }
        return batches;
    }
    
    /**
     * 处理单个模拟批次
     */
    private static String processMockBatch(MockBatch batch, SimpleBatchProgressTracker progressTracker) {
        try {
            log.debug("开始处理批次 {}: {}", batch.getBatchNumber(), batch.getDescription());
            
            // 模拟AI处理时间（不同批次耗时不同）
            int processingTime = batch.getProcessingTimeMs();
            Thread.sleep(processingTime);
            
            // 模拟5%的失败率
            if (Math.random() < 0.05) {
                throw new RuntimeException("模拟处理失败");
            }
            
            String result = "SUCCESS_" + batch.getBatchNumber();
            
            // 批次完成，更新进度
            progressTracker.onBatchCompleted(batch.getBatchNumber());
            
            log.debug("批次 {} 处理完成，耗时 {}ms", batch.getBatchNumber(), processingTime);
            return result;
            
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            progressTracker.onBatchError(batch.getBatchNumber(), "处理中断");
            return "INTERRUPTED_" + batch.getBatchNumber();
        } catch (Exception e) {
            log.warn("批次 {} 处理异常: {}", batch.getBatchNumber(), e.getMessage());
            progressTracker.onBatchError(batch.getBatchNumber(), e.getMessage());
            return "ERROR_" + batch.getBatchNumber();
        }
    }
    
    /**
     * 模拟批次数据
     */
    private static class MockBatch {
        private final int batchNumber;
        private final String description;
        private final int processingTimeMs;
        
        public MockBatch(int batchNumber, String description, int processingTimeMs) {
            this.batchNumber = batchNumber;
            this.description = description;
            this.processingTimeMs = processingTimeMs;
        }
        
        public int getBatchNumber() { return batchNumber; }
        public String getDescription() { return description; }
        public int getProcessingTimeMs() { return processingTimeMs; }
    }
    
    /**
     * 演示用的进度回调实现
     */
    private static class DemoProgressCallback implements ProgressCallback {
        @Override
        public void onProgress(int current, int total, String message) {
            if (current == -1 && total == -1) {
                // 状态更新
                log.info("[进度状态] {}", message);
            } else {
                // 进度更新
                double percentage = total > 0 ? (double) current / total * 100 : 0;
                log.info("[进度更新] {:.1f}% - {}", percentage, message);
            }
        }
    }
    
    /**
     * 主函数演示
     */
    public static void main(String[] args) {
        demonstrateParallelProcessing();
    }
}